class SessionController < ActionController::Base
  include AppMethod

  layout 'login'
  helper_method :current_user
  def login
    if current_user.present?
      flash[:notice] = '请先退出登录！'
      return redirect_to '/'
    end
    @user = Base::User.new
  end

  def do_login
    users = Base::User.valid_users(params[:base_user])
    browser = Browser.new(request.user_agent)
    platform = "#{browser.platform.name}-#{browser.name}"
    if users.length==1
      user = users.first
      session[:current_user_id] = user.id
      session[:current_customer_id] = user.customer_id
      session[:expired_at] = Time.now+2.hours
      user.update(last_login_at: Time.now)
      set_current_user
      Log::LoginHistory.create(user_id: user.id, username: user.mobile, status: 1, platform: platform, customer_id: user.customer_id, ip: request.ip)
      flash[:notice] = '登陆成功！'
      redirect_to session[:login_referer]||root_path
    elsif users.length>1
      options = "<option></option>"
      users.each do |x|
        options << "<option value='#{x.customer_id}'>#{x.customer.name}</option>"
      end
      render js: "show_notice('请选择需要登陆的公司');"\
                  "$('#select-customer').removeClass('hide');"\
                 "$('#base_user_customer_id').html(#{options.to_json})"
    else
      Log::LoginHistory.create(username: params[:base_user][:username], status: 2, platform: platform, ip: request.ip)
      error_notice '登陆失败，请检查用户名密码！'
    end
  end

  def logout
    clear_session
    flash[:notice] = '成功退出！'
    redirect_to login_path
  end


  def register
    @html_title = '企业注册'
  end

  def do_register
    c = Customer.new(name: params[:customer_name], short_name: params[:short_name], master_mobile: params[:mobile])
    if c.valid?
      c.save
      Base::User.create!(name_cn: params[:name_cn], mobile: params[:mobile], password: params[:password], customer_id: c.id)
      flash[:notice] = '注册成功！'
      redirect_to root_path
    else
      error_notice(c)
    end
  end

  def forgot
    @html_title = '忘记密码'
  end

  def do_forgot
    user = Base::User.active.where(mobile: params[:mobile])
    return error_notice('该手机号尚未注册或已被禁用！') if user.blank?
    # update_all 是要直接更新数据库的，所以要加密一遍
    user.update_all(password: Digest::MD5.hexdigest(params[:password]))
    flash[:notice] = '密码重置成功！'
    redirect_to root_path
  end

  def send_validate_code
    r = Log::CodeHistory.send_code(params[:mobile], params[:type])
    if r.valid?
      render json: {result: true, msg: (Rails.env=='development' ? r.code_num : '发送成功！')}
    else
      render json: {result: false, msg: r.errors.values.join(',')}
    end

  end

  def validate_code
    render json: Log::CodeHistory.validate_code(params[:mobile],params[:type], params[:code])
  end


end
